<?php
namespace app\admin\controller;

class Coupon extends Auth{
	public function __construct()
	{
		parent::__construct();
        $this->isLogin();
		$this->User = D('User');
	}
	
	public function index()
	{ 
		//判断某用户下是否有至少一个优惠券，如果有就将get 设置为1（在提交订单时写入）,使用group分组，不必从member中查询
        $where['get']=array('eq',0);
        $info = M('Member')->where($where)->select();
        $this->assign('info',$info);
        return $this->fetch();
	}

    /**
    * 生成优惠券
    **/
	public function generate()
	{
       //楼盘类别
		$pantype = M('term')->where('display_nav=1')->select();
		$this->assign('pantype',$pantype);
		//生成优惠券
		if(IS_POST){
	     $panid = $_POST['panid'];
		 $name = $_POST['name'];
		 $money = $_POST['money'];
		 //计算出有效期
		 $days = $_POST['tianshu'];
		 $expiry_date = time()+$days*24*3600;
         //优惠券描述
         $content = $_POST['content'];
		 $nums = !empty($_POST['nums'])?$_POST['nums']:10;
		 $time = time();
		 $now_time = date('Ymd',time());
		 //没啥意义，哈哈,乐意
		 $chars = $money."ABCDEFGHIJKLMNOPQRSTUVWXYZa".$nums."bcdefghijklmnopqrstuvwxyz01235689";
		//生成优惠券
		 $code=[];
          for($i=1;$i<=$nums;$i++){
          	 $code[]=random(10,$chars);
          }
           for($i=0;$i<=$nums-1;$i++){
           	$data[]=array('name'=>$name,'panid'=>$panid,'money'=>$money,'code'=>$now_time.$code[$i],'time'=>$time,'expiry_date'=>$expiry_date,'content'=>$content);
           }
          $info = M('coupon')->addAll($data);
           	 if($info){
	         	return $this->success('生成优惠券成功',U('Coupon/index'));
	         }else{
	         	return $this->error('生成优惠券失败',U('Coupon/generate'));
	         }

	   }
		
		return $this->fetch();
	}

    /**
    * 发放优惠券
    **/
	public function grant()
	{

		
        //楼盘类别
		$pantype = M('term')->where('display_nav=1')->select();
		$this->assign('pantype',$pantype);
		//发放优惠券到对应的楼盘,term表中coupon中记录数量
		if(IS_POST){
		$id=$_POST['id'];
		$nums = $_POST['nums'];
        $giv_coupon = M('term')->where('id='.$id)->setInc('coupon',$nums);;
	         if($giv_coupon){
	         	    $where['give']=0;
	         	    $where['panid']=$id;
		         	M('coupon')->where($where)->limit($nums)->setField('give','1');
	         	return $this->success('发放成功',U('Coupon/index'));
	         }else{
	         	return $this->error('发放失败',U('Coupon/grant'));
	         }
			
		}

		return $this->fetch();
	}

	/**
	*查看某个会员的优惠券列表
	**/
   public function list_coupon($mid)
   {
     $list = M('coupon')->where('his='.$mid)->select();
     $this->assign('list',$list);
   	 return $this->fetch();
   }
   public function list_wei_coupon()
   {
   	 $where['his']=array('neq',0);
   	 $where['use']=array('neq',1);
     $list = M('coupon')->where($where)->select();
     $this->assign('list',$list);
   	 return $this->fetch();
   }

   public function list_yi_coupon()
   {
   	 $where['his']=array('neq',0);
   	 $where['use']=array('eq',1);
     $list = M('coupon')->where($where)->select();
     $this->assign('list',$list);
   	 return $this->fetch();
   }
	
   public function ajax()
   {
   	$id = $_POST['lid'];
   	$where['panid']=$id;
   	$where['give']=0;
   	$num = M('Coupon')->where($where)->count();
   	echo json_encode($num."张");
   }

	/**
	*  作废指定优惠券
	*
	**/
    public function zuofei($id,$mid)
    {
    	$info = M('coupon')->where('id='.$id)->delete();
           	 if($info){
	         	return $this->success('作废成功',U('Coupon/list_coupon',array('mid'=>$mid)));
	         }else{
	         	return $this->error('作废失败',U('Coupon/list_coupon',array('mid'=>$mid)));
	         }    	
    }

   	/**
	*标记优惠券已使用
	**/

  public function tocheck()
  {
  	//在coupon中 将对应的优惠码中的use状态改为1，即表示已使用。
  	//其中，如果不存在，提示无此优惠券或已使用
  	if(IS_POST){
		  	$check_code = I('post.code');
		  	$where['code']=$check_code;
		  	$info = M('coupon')->where($where)->find();
		  	if($info){
			    if($info['use'] ==0){
			    	 $check = M('coupon')->where($where)->setField('use',1);
			    	 if($check){
			    	 	return $this->success('核对成功，此优惠券已被标记为使用状态',U('Coupon/tocheck'));
			    	 }else{
			    	 	return $this->error('核对失败，请重新操作',U('Coupon/tocheck'));
			    	 }
			    	
			    }else{
			    	return $this->error('优惠券已经使用',U('Coupon/tocheck'));
			    }  
			   }else{
			   	   return $this->error('此优惠券不存在，请核对',U('Coupon/tocheck'));
			   }		
  	}else{
         if(isset($_GET['code'])){
		  	$what['code'] = $_GET['code'];
		    $check = M('coupon')->where($what)->setField('use',1);
			 if($check){
			 	return $this->success('核对成功，此优惠券已被标记为使用状态',U('Coupon/tocheck'));
			 }else{
			 	return $this->error('核对失败，请重新操作',U('Coupon/tocheck'));
			 }		
		 }

  	}

  	return $this->fetch();
  }
    /**
     * 批量删除
     * @param array $del_id 待删除ID的数组
     */
    public function delid($del_id)
    {
        $map['id']  = array('in',$del_id);
        $delet_id = M('coupon')->where($map)->delete();
        if($delet_id){
            manage_log_success();
        }else{
            manage_log_error();
        }
    }

/**
* 微信，支付宝账单
**/
public function zhifu_weichat()
{
	$where['zhifu_type']=1;
	$list = M('coupon')->where($where)->select();
	//向原数据追加数据，传入数据表名称，传入原数组个数，传入关联字段，第一个为元数组，第二位关联数组
	$info = [];
	for($i=0;$i<=count($list)-1;$i++){
		$info[] = M('member')->where('id='.$list[$i]['his'])->find();
		array_push($list[$i],$info[$i]['uname'],$info[$i]['id']);
	}
	$this->assign('list',$list);
	return $this->fetch();
}

public function zhifu_alipay()
{
	$where['zhifu_type']=2;
	$list = M('coupon')->where($where)->select();
		//向原数据追加数据，传入数据表名称，传入原数组个数，传入关联字段，第一个为元数组，第二位关联数组
	$info = [];
	for($i=0;$i<=count($list)-1;$i++){
		$info[] = M('member')->where('id='.$list[$i]['his'])->find();
		array_push($list[$i],$info[$i]['uname'],$info[$i]['id']);
	}
	$this->assign('list',$list);
	return $this->fetch();
}
	
public function zhifu_wei()
{
	$where['status']=0;
	$where['lock']=1;
	$where['zhifu_type']=0;
	$list = M('coupon')->where($where)->select();
	//向原数据追加数据，传入数据表名称，传入原数组个数，传入关联字段，第一个为元数组，第二位关联数组
	$info = [];
	for($i=0;$i<=count($list)-1;$i++){
		$info[] = M('member')->where('id='.$list[$i]['his'])->find();
		array_push($list[$i],$info[$i]['uname'],$info[$i]['id']);
	}
	$this->assign('list',$list);
	return $this->fetch();
}


//导出excel
public function order_daochu($type)
{
	$where['status']=1;
	$where['lock']=1;
	$where['zhifu_type']=$type;
	$list = M('coupon')->where($where)->select();
	//向原数据追加数据，传入数据表名称，传入原数组个数，传入关联字段，第一个为元数组，第二位关联数组
	$info = [];
	for($i=0;$i<=count($list)-1;$i++){
		$info[] = M('member')->where('id='.$list[$i]['his'])->find();
		array_push($list[$i],$info[$i]['uname']);
	}


	Vendor('PHPExcel.PHPExcel');
	$objPhpExcel = new \PHPExcel();
	$objSheet = $objPhpExcel->getActiveSheet();//获得当前活动sheet的操作对象
	$objSheet->setTitle('excel'); //给当前活动sheet设置名称

	$objSheet->setCellvalue('A1',"ID")
	         ->setCellvalue('B1','所属用户')
	         ->setCellvalue('C1','优惠码')
	         ->setCellvalue('D1','过期时间')
	         ->setCellvalue('E1','支付方式');
  if($type == 1){
	   foreach($list as $key=>$value){
	   	    $c = $key+2;
	    	$objSheet->setCellvalue('A'.$c,$value['id'])
	    	         ->setCellvalue('B'.$c,$value['id'])
	    	         ->setCellvalue('C'.$c,$value['code'])
	    	         ->setCellvalue('E'.$c,"微信支付");        
	    }

  }elseif($type == 2){
	   foreach($list as $key=>$value){
	   	    $c = $key+2;
	    	$objSheet->setCellvalue('A'.$c,$value['id'])
	    	         ->setCellvalue('B'.$c,$value[0])
	    	         ->setCellvalue('C'.$c,$value['code'])
	    	         ->setCellvalue('E'.$c,"支付宝支付");        
	    }

  }



	$objWriter = \PHPExcel_IOFactory::createWriter($objPhpExcel,'Excel2007');//生成文件
    $this->download();
    $objWriter->save('php://output');
}

public function daochu()
{
	$where['status']=0;
	$where['lock']=1;
	$where['zhifu_type']=0;
	$list = M('coupon')->where($where)->select();
	//向原数据追加数据，传入数据表名称，传入原数组个数，传入关联字段，第一个为元数组，第二位关联数组
	$info = [];
	for($i=0;$i<=count($list)-1;$i++){
		$info[] = M('member')->where('id='.$list[$i]['his'])->find();
		array_push($list[$i],$info[$i]['uname']);
	}

	Vendor('PHPExcel.PHPExcel');
	$objPhpExcel = new \PHPExcel();
	$objSheet = $objPhpExcel->getActiveSheet();//获得当前活动sheet的操作对象
	$objSheet->setTitle('excel'); //给当前活动sheet设置名称

	$objSheet->setCellvalue('A1',"ID")
	         ->setCellvalue('B1','所属用户')
	         ->setCellvalue('C1','优惠码');
   
   foreach($list as $key=>$value){
   	    $c = $key+2;
    	$objSheet->setCellvalue('A'.$c,$value['id'])
    	         ->setCellvalue('B'.$c,$value[0])
    	         ->setCellvalue('C'.$c,$value['code']);
    }

	$objWriter = \PHPExcel_IOFactory::createWriter($objPhpExcel,'Excel2007');//生成文件
    $this->download();
    $objWriter->save('php://output');
}

public function download()
{
	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition: attachment;filename="01simple.xlsx"');
	header('Cache-Control: max-age=0');
}




}